﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ComicIsland.Common;
using ComicIsland.Common.Entities;

/**
 * 创建时间：2014/12/18 15:31:56
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.App.Views.DownloadComicViews
{
    public class DownloadComicDataContextHelper
    {
        DownloadComicDataContext db;
        public DownloadComicDataContextHelper(DownloadComicDataContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 数据是否有效
        /// </summary>
        /// <returns></returns>
        public bool IsValidComicIdAndPartId(TableDownloadComic item)
        {
            if (item == null)
            {
                return false;
            }
            if (item.ComicId <= 0 || item.PartId <= 0)
            {
                return false;
            }

            return true;
        }

        public void OutputTableInfo()
        {
            var table = this.GetTable();
            if (table != null && table.Count() > 0)
            {
                foreach (TableDownloadComic item in table)
                {
                    LogHelper.LogInfo(item.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }

        #region 下载队列数据操作
        /// <summary>
        /// 从表中获取一条等待下载的图片数据项
        /// </summary>
        /// <param name="comicId"></param>
        /// <param name="partId"></param>
        /// <returns></returns>
        public TableDownloadComic GetOneToBackgroundTransfer(int comicId, int partId)
        {
            var items = GetTableComicsChapter(comicId, partId);
            TableDownloadComic item = items.Where(p => p.DownloadStatusComic.Equals(DownloadComicChapterStatus.Pending.ToString())
                && p.DownloadStatusComicChapter.Equals(DownloadComicChapterStatus.Pending.ToString())
                && p.DownloadStatusComicChapterImage.Equals(DownloadComicChapterStatus.Pending.ToString()))
                .FirstOrDefault<TableDownloadComic>();
            return item;
        }

        public void UpdateDownloadStatusComicChapterImage(int comicId, int partId, string imageUrl, DownloadComicChapterStatus status)
        {
            try
            {
                var items = this.GetTable();
                if (items == null)
                    return;

                var item = items.Where(p => p.ComicId == comicId && p.PartId == partId && p.ImageUrl.Equals(imageUrl)).FirstOrDefault<TableDownloadComic>();
                if (item == null)
                    return;
                //
                item.DownloadStatusComicChapterImage = status.ToString();
                Update(item);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        public void UpdateDownloadStatusComicChapter(int comicId, int partId, DownloadComicChapterStatus status)
        {
            try
            {
                var items = this.GetTable();
                if (items == null)
                    return;

                var updateItems = items.Where(p => p.ComicId == comicId && p.PartId == partId).ToList<TableDownloadComic>();

                if (updateItems == null && updateItems.Count > 0)
                {
 //foreach(TableDownloadComic )
                }  
                //
                //item.DownloadStatusComicChapter = status.ToString();
                //Update(item);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        public void UpdateDownloadStatusComic(int comicId, DownloadComicChapterStatus status)
        {
            try
            {
                var items = this.GetTable();
                if (items == null)
                    return;

                var item = items.Where(p => p.ComicId == comicId).FirstOrDefault<TableDownloadComic>();
                if (item == null)
                    return;
                //
                item.DownloadStatusComic = status.ToString();
                Update(item);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }
        #endregion  下载队列数据操作

        #region 获取数据
        public Table<TableDownloadComic> GetTable()
        {
            try
            {
                return this.db.GetTable<TableDownloadComic>();
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                return null;
            }
        }

        public List<TableDownloadComic> GetTableList()
        {
            var table = this.GetTable();
            if (table != null && table.Count() > 0)
            {
                return table.ToList<TableDownloadComic>();
            }
            return null;
        }

        public ObservableCollection<TableDownloadComic> GetTableObservableCollection()
        {
            var list = GetTableList();
            if (list != null && list.Count > 0)
            {
                return new ObservableCollection<TableDownloadComic>(list);
            }
            return null;
        }

        public ObservableCollection<TableDownloadComic> GetTableComicsDistinct()
        {
            ObservableCollection<TableDownloadComic> items = new ObservableCollection<TableDownloadComic>();
            var table = GetTableObservableCollection();
            if (table != null && table.Count() > 0)
            {
                //var distinctComics = table.DistinctBy(p => new { p.ComicId, p.ComicTitle, p.CoverUrl });
                //var hh = distinctComics as ObservableCollection<TableDownloadComic>;
                var distinctComic = table.GroupBy(p => new { p.ComicId, p.ComicTitle, p.CoverUrl }).Select(g => g).ToList();
                if (distinctComic != null && distinctComic.Count > 0)
                {
                    foreach (var item in distinctComic)
                    {
                        items.Add(new TableDownloadComic()
                        {
                            ComicId = item.Key.ComicId,
                            ComicTitle = item.Key.ComicTitle,
                            CoverUrl = item.Key.CoverUrl
                        });
                    }
                }
            }

            return items;
        }

        /// <summary>
        /// 获取comicId漫画的所有章节
        /// </summary>
        /// <param name="comicId"></param>
        /// <returns></returns>
        public ObservableCollection<TableDownloadComic> GetTableComicsChapterDistinct(int comicId)
        {
            ObservableCollection<TableDownloadComic> items = new ObservableCollection<TableDownloadComic>();
            var table = GetTableObservableCollection();
            if (table != null && table.Count() > 0)
            {
                var distinctComic = table.GroupBy(p => new { p.ComicId, p.ComicTitle, p.CoverUrl, p.PartId, p.ComicIdAndPartId }).Select(g => g).ToList();
                if (distinctComic != null && distinctComic.Count > 0)
                {
                    foreach (var item in distinctComic)
                    {
                        if (item.Key.ComicId != comicId)
                            continue;
                        items.Add(new TableDownloadComic()
                        {
                            ComicId = item.Key.ComicId,
                            ComicTitle = item.Key.ComicTitle,
                            CoverUrl = item.Key.CoverUrl,
                            PartId = item.Key.PartId,
                            ComicIdAndPartId = item.Key.ComicIdAndPartId
                        });
                    }
                }
            }

            return items;
        }

        /// <summary>
        /// 获取comicId漫画的partId章节的列表信息
        /// </summary>
        /// <param name="comicId"></param>
        /// <param name="partId"></param>
        /// <returns></returns>
        public ObservableCollection<TableDownloadComic> GetTableComicsChapter(int comicId, int partId)
        {
            ObservableCollection<TableDownloadComic> items = new ObservableCollection<TableDownloadComic>();
            var table = GetTableObservableCollection();
            if (table != null && table.Count() > 0)
            {
                var result = (from p in table where p.ComicId == comicId && p.PartId == partId select p).ToList<TableDownloadComic>();
                if (result != null && result.Count > 0)
                {
                    return new ObservableCollection<TableDownloadComic>(result);
                }
            }

            return items;
        }



        /// <summary>
        /// 查询数据
        /// <para>根据漫画Id,获取整部漫画信息</para>
        /// </summary>
        /// <param name="comicId"></param>
        /// <returns></returns>
        public List<TableDownloadComic> GetOneComicByComicId(int comicId)
        {
            try
            {
                Table<TableDownloadComic> table = this.db.GetTable<TableDownloadComic>();
                if (table != null)
                {
                    return (from p in table where p.ComicId.Equals(comicId) select p).ToList<TableDownloadComic>();
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                return null;
            }
            return null;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="comicId"></param>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        public TableDownloadComic GetOne(int comicId, int chapterId)
        {
            try
            {
                Table<TableDownloadComic> table = this.db.GetTable<TableDownloadComic>();
                if (table != null)
                {
                    var item = (from p in table where p.ComicId == comicId && p.PartId == chapterId select p).FirstOrDefault<TableDownloadComic>();
                    return item;
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                return null;
            }
            return null;
        }
        #endregion 获取数据



        /// <summary>
        /// 更新数据
        /// </summary>        
        public void InsertOrUpdate(ObservableCollection<TableDownloadComic> items)
        {
            if (items == null)
                return;

            foreach (TableDownloadComic item in items)
            {
                if (item == null)
                    continue;
                if (item.ComicId <= 0 || item.PartId <= 0)
                    continue;
                TableDownloadComic row = GetOne(item.ComicId, item.PartId);
                if (row == null)
                {
                    //新增
                    try
                    {
                        db.TableDownloadComic.InsertOnSubmit(item);
                        db.SubmitChanges();
                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    }
                }
                else
                {
                    //更新
                    Update(row, item);
                }
            }
        }

        /// <summary>
        /// 将latestItem赋值给originalItem后更新originalItem至表中
        /// </summary>
        /// <param name="originalItem"></param>
        /// <param name="latestItem"></param>
        private void Update(TableDownloadComic originalItem, TableDownloadComic latestItem)
        {
            try
            {
                //
                originalItem.ComicTitle = latestItem.ComicTitle;
                originalItem.CoverUrl = latestItem.CoverUrl;
                originalItem.DownloadStatusComic = latestItem.DownloadStatusComic;
                //
                originalItem.PartId = latestItem.PartId;
                originalItem.Name = latestItem.Name;
                originalItem.Partsize = latestItem.Partsize;
                originalItem.Partnumber = latestItem.Partnumber;
                originalItem.Totalpage = latestItem.Totalpage;
                originalItem.Msourceparturl = latestItem.Msourceparturl;
                originalItem.Sourceparturl = latestItem.Sourceparturl;
                originalItem.DownloadStatusComicChapter = latestItem.DownloadStatusComicChapter;
                //
                originalItem.ImageUrl = latestItem.ImageUrl;
                originalItem.Referer = latestItem.Referer;
                originalItem.DownloadStatusComicChapterImage = latestItem.DownloadStatusComicChapterImage;
                //
                db.TableDownloadComic.InsertOnSubmit(originalItem);
                db.SubmitChanges();
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }


        private void Update(TableDownloadComic latestItem)
        {
            try
            {
                db.TableDownloadComic.InsertOnSubmit(latestItem);
                db.SubmitChanges();
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }




















    }
}
